package com.hcbd.tdwt.base.view;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.ui.common.dialog.BluetoothDialog;
import com.pangu.bdsdk2021.bluetooth.BluetoothManage;
import com.pangu.bdsdk2021.bluetooth.BluetoothManageInterface;


import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;
public class BDServiceStatusRelativeLayout extends RelativeLayout implements BluetoothManageInterface {
    private ImageView status_img,signal,entry;
    private RelativeLayout bgRL;
    private TextView bdService;
    private Context mContext;
    private Activity activity;
    //是否刷新终端信息
    private boolean isRefreshing = false;
    private BluetoothDialog bluetoothDialog;

    public BDServiceStatusRelativeLayout(Context context){
        super(context);
        init(context,null);
    }

    public BDServiceStatusRelativeLayout(Context context, AttributeSet attrs){
        super(context,attrs);
        init(context,attrs);
    }

    public BDServiceStatusRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr){
        super(context,attrs,defStyleAttr);
        init(context,attrs);
    }
    private void init(Context context, AttributeSet attrs){
        mContext=context;
        activity=(Activity)mContext;
        deviceList=new ArrayList<>();
        bluetoothDialog=new BluetoothDialog(context);
        View view =inflate(context, R.layout.bd_service_status,this);
        status_img=view.findViewById(R.id.status_img);
        bdService=view.findViewById(R.id.bdService);
        signal=view.findViewById(R.id.signal_img);
        entry=view.findViewById(R.id.entry_img);
        bgRL=view.findViewById(R.id.bgRL);
        BluetoothManage.getInstance().init(context,this);
        this.setOnClickListener(v -> {
            if(!BluetoothManage.getInstance().isEnable()){
                BluetoothAdapter.getDefaultAdapter().enable();
                return;
            }

            if(BeidouBoxParams.isBoxConnectNormal){


            }else{
                deviceList.clear();
                BluetoothManage.getInstance().startDiscovery();
                BluetoothDialog.show(bluetoothDialog);
            }

        });
    }
    public void setStatusImg(Drawable img){
        status_img.setBackground(img);
    }
    public void setSignalImg(Drawable img){
        signal.setBackground(img);
    }
    public void setEntryImg(Drawable img){
        entry.setBackground(img);
    }
    public void setBdService(String str){
        bdService.setText(str);
    }

    /**
     * 刷新终端信息
     */
    public void refreshStatus() {
        if (BeidouBoxParams.isBoxConnectNormal) {
            signal.setVisibility(VISIBLE);
            bgRL.setBackgroundColor(getResources().getColor(R.color.white));
            bdService.setTextColor(getResources().getColor(R.color.black));
            status_img.setImageResource(R.drawable.connect_box_icon);
            if (BeidouBoxParams.userCardNumber == null) {
                bdService.setText("未点击北斗设备,点击连接");
            } else {
                bdService.setText(String.format("北斗服务已打开(%s)", BeidouBoxParams.userCardNumber));
            }
            int beidouSignal = BeidouBoxParams.getBdSignal();

            if (beidouSignal == 0) {
                signal.setImageResource(R.drawable.signal1);
            } else if (beidouSignal == 1) {
                signal.setImageResource(R.drawable.signal2);
            } else if (beidouSignal == 2) {
                signal.setImageResource(R.drawable.signal3);
            } else if (beidouSignal == 3) {
                signal.setImageResource(R.drawable.signal4);
            } else {
                signal.setImageResource(R.drawable.signal5);
            }
        } else {
            bgRL.setBackgroundColor(getResources().getColor(R.color.lightRed));
            bdService.setTextColor(getResources().getColor(R.color.red));
            bdService.setText("未点击北斗设备,点击连接");
            status_img.setImageResource(R.drawable.unconnect_box_icon);
            signal.setVisibility(GONE);
        }
    }
    /**
     * 自动刷新
     */
    public void autoRefresh() {
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (isRefreshing) {
                        Message msg = new Message();
                        msg.what = 1;
                        adapterHandler.sendMessage(msg);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    Log.e("InfoMessage", e.toString());
                }
            }
        }).start();
    }
    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private Handler adapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    refreshStatus();
                    break;
            }
        }
    };
    public void setIsRefreshing(boolean isRefreshing){
        this.isRefreshing=isRefreshing;
    }
    private List<BluetoothDevice> deviceList;
    @Override
    public void onScanningResult(List<BluetoothDevice> list, BluetoothDevice bluetoothDevice) {
        if (bluetoothDevice.getName() == null) return;
        if (deviceList.size() == 0) {
            deviceList.add(bluetoothDevice);
        }
        boolean isExist = false;
        for (int i = 0; i < deviceList.size(); i++) {
            if (bluetoothDevice.getAddress().equals(deviceList.get(i).getAddress())) {
                isExist = true;
            }
        }
        if (!isExist) {
            deviceList.add(bluetoothDevice);
        }
        bluetoothDialog.init(deviceList);
    }

    @Override
    public void onConnectSucceed(BluetoothDevice bluetoothDevice) {
        BeidouBoxParams.isBoxConnectNormal=true;
        activity.runOnUiThread(() -> {
            MainApp.getInstance().showMsg("连接成功!");
           // MainApplication.getInstance().hideLoading();
        });
    }

    @Override
    public void onConnectError() {
        activity.runOnUiThread(() -> {
            MainApp.getInstance().showMsg("连接失败!");
           // MainApplication.getInstance().hideLoading();
        });
    }

    @Override
    public void onDisconnect() {
        activity.runOnUiThread(() -> {
            MainApp.getInstance().showMsg("断开连接!");
        //    MainApplication.getInstance().hideLoading();
        });
    }

    @Override
    public void sendDataCallback(int i) {

    }
}
